package com.xiaoliang.controller;

import com.xiaoliang.entry.User;
import com.xiaoliang.service.impl.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author XIAOLIANG
 * @ClassName UserController.java
 * @Description TODO
 * @createTime 2021年03月02日 20:10:00
 */
@Controller
public class UserController {

	UserServiceImpl userService = new UserServiceImpl();


//	@GetMapping("/goLogin")
//	public String goLogin(){
//		return "login.html";
//	}

	@ResponseBody
	@RequestMapping(value = "/login",produces = "application/json;charset=utf-8")
	public String login(HttpSession session, String code, String username, String password){

		System.out.println("login");
		System.out.println(username);
		System.out.println(code);
		Object verificationCode = session.getAttribute("verificationCode");
		String realCode = String.valueOf(verificationCode);




		boolean loginAccess = userService.login(new User(username, password));

		if (!realCode.equals(code)){
			session.setAttribute("msg","验证码输入错误");  //验证码 导致登录失败
			System.out.println("验证码输入错误");
			return "验证码输入错误";
		}

		if (loginAccess){
			session.setAttribute("username",username);
			session.setAttribute("login","ok");
			System.out.println("登录ok");

			return "success";

		}else {

			session.setAttribute("msg","登录失败,请检查用户账号和密码");  //账号密码导致登录失败
			System.out.println("登录失败");
			return "登录失败,请检查用户账号和密码";

		}

	}

	@RequestMapping("/register")
	public String register(User user,HttpSession session){


		boolean register= false;
		try {
			register = userService.register(user);
		} catch (Exception e) {
			e.printStackTrace();
		}

		session.setAttribute("username",user.getUsername());
		if (register){
			session.setAttribute("msg","注册成功, 请登录!");

			return "redirect:/login.html";

		}else {
			session.setAttribute("msg","注册失败! 用户名重复");
			session.setAttribute("password",user.getPassword());
			return "redirect:/regist.jsp";
		}



	}

}
